
package com.htd.htdapmservice.xxljob;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.acooly.core.utils.Ids;
import com.alibaba.fastjson.JSONObject;
import com.htd.htdapmapi.alarm.dto.BussinessAlarmDto;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.constants.AlarmConstants;
import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmcommon.enums.AlarmSendStatus;
import com.htd.htdapmcommon.enums.AlarmsLevelEnum;
import com.htd.htdapmcommon.enums.AlarmsStatusEnum;
import com.htd.htdapmcommon.util.DateUtil;
import com.htd.htdapmdmo.LogAnalyzeErrorRecord;
import com.htd.htdapmservice.service.intf.ElasticsearchService;
import com.htd.htdapmservice.service.intf.LogAnalyzeErrorRecordService;
import com.htd.htdapmservice.service.intf.OneAlertKeyService;
import com.htd.htdapmservice.service.intf.OneAlertService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;

/**
 * 异常日志告警task
 */
@JobHandler(value="logAnalyzeErrorRecordJobHandler")
@Component
public class LogAnalyzeErrorRecordJobHandler extends IJobHandler {
    private static final Logger logger = LoggerFactory.getLogger(LogAnalyzeErrorRecordJobHandler.class);
    
	@Autowired
    private ElasticsearchService elasticsearchService;
    @Autowired
    private LogAnalyzeErrorRecordService logAnalyzeErrorRecordService;
    @Autowired
    private OneAlertService  oneAlertService;

    @Autowired
    private OneAlertKeyService oneAlertKeyService;
    
    @Resource(name="client4Bussiness")
	private TransportClient client4Bussiness;
	
	@Override
	public ReturnT<String> execute(String param) throws Exception {
		
        logger.info("logAnalyzeErrorRecordJobHandler Entrance, param : {}", new Object[]{JSONObject.toJSONString(param)});
        List<LogAnalyzeErrorRecord> logAnalyzeErrorRecordList = new ArrayList<LogAnalyzeErrorRecord>();
        try{
            //获取当前小时内的错误日志
            logAnalyzeErrorRecordList = elasticsearchService.getNewLogAnalyzeErrorRecordList();
            logger.info("分析日志查询异常数据{}",logAnalyzeErrorRecordList.size());
            if (logAnalyzeErrorRecordList!=null &&logAnalyzeErrorRecordList.size()>0) {
                for (LogAnalyzeErrorRecord logAnalyzeErrorRecord:logAnalyzeErrorRecordList) {
                    AlarmInto alarmInto = new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(logAnalyzeErrorRecord.getProductTypeCode());
                    alarmInto.setAlarmsDetail(logAnalyzeErrorRecord.getAlarmsDetail());
                    if(oneAlertKeyService.findOneAlertKeyByProductCode(logAnalyzeErrorRecord.getProductTypeCode())!=null){
                        alarmInto.setAlarmsTitle(oneAlertKeyService.findOneAlertKeyByProductCode(logAnalyzeErrorRecord.getProductTypeCode()).getProductName()+"日志异常");
                    }else {
                        alarmInto.setAlarmsTitle("日志异常");
                    }
                    //告警成功入ES
                    String  alarmsId =Ids.getDid();
                    alarmInto.setAlarmsId(alarmsId);
                	setBusinessAlarm2ES(alarmInto);
                	//
                    AlarmResult alarmResult = oneAlertService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        logAnalyzeErrorRecord.setSendStatus(AlarmSendStatus.SEND_YES);
                        logAnalyzeErrorRecordService.insertLogAnalyzeErrorRecord(logAnalyzeErrorRecord);
                       
                    }else{
                        logAnalyzeErrorRecordService.insertLogAnalyzeErrorRecord(logAnalyzeErrorRecord);
                    }
                }
            }
            
            
        } catch (Exception e){
            logger.error("logAnalyzeErrorRecordJobHandler error:", e);
            return FAIL;
        }
        
		return SUCCESS;
	}
	
	
	private void setBusinessAlarm2ES(AlarmInto alarmInto){
		BussinessAlarmDto dto = new BussinessAlarmDto();
		try {
			BeanUtils.copyProperties(dto,alarmInto);
			dto.setSourceFrom(AlarmConstants.SOURCE_FROM_4);
			dto.setAlarmStatus(AlarmsStatusEnum.ACTIVE.getCode());
			dto.setAlarmTime(DateUtil.getTime4ES());
			if(StringUtils.isEmpty(alarmInto.getAlarmsId())){
				return;
			}
			IndexResponse response = new IndexResponse();
			IndexRequestBuilder builder = client4Bussiness.prepareIndex(AlarmConstants.BUSINESS_INDEX_NAME,
					AlarmConstants.BUSINESS_TYPE_NAME, dto.getAlarmsId());
			builder.setSource(JSONObject.toJSONString(dto), XContentType.JSON);
			response = builder.execute().actionGet();
			logger.info("业务告警进入ES response:{}",JSONObject.toJSONString(response));
		} catch (Exception e) {
			logger.error("bean copy 异常:",e);
		}
	}

}


